/**
 * Created by sxx on 2017/5/3.
 */
import "./index.less";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.zh-CN.js";

import bidListTpl from "./apply_list.handlebars";
import paginationTpl from "./paging.handlebars";

let token = sessionStorage.getItem('token');
let reseIndex = sessionStorage.getItem('reseIndex');
let orgId = sessionStorage.getItem('orgId');
if (orgId == null || orgId =='') {
    location.href = HOST_FRT+'/logins/login.html';
}
var ApplyList = {
    pageNo: 1,
    pageSize: 20,
    maxPage: 1,
    isFirstPage: false,
    isLastPage: false,
    total: 0,
    data:{},
    init: function() {
        this.getData()
            .then(this.renderList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    },
    getData: function() {
        let self = ApplyList;
        return new Promise((resolve, reject) => {
            let data = {};
            let header = {
                    'access_token': token,
                    'login_type': 'ums',
                    'pageNo': self.pageNo,
                    'pageSize': self.pageSize,
                    'orgId': orgId
                };
            if(self.data.splrNam!='' && self.data.splrNam!=null){
                data.splrFullName = self.data.splrNam;
            }
            $.ajax({
                url: HOST_ADDR + '/cpmp/splrWdot/getSplrList/',
                type: 'post',
                dataType: 'json',
                headers: header,
                data:JSON.stringify(data),
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        console.log(resp);
                        resolve(resp);
                    } else {
                        alert(resp.msgInf);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });
    },
    // 渲染列表

    renderList: function(resp) {
        let self = ApplyList;
        // 处理数据begin
        let splrStatus = {
            "01":"注册",
            "02":"准入申请",
            "03":"预备供方",
            "04":"开发申请",
            "05":"合格供方",
            "06":"淘汰",
            "07":"黑名单",
            "08":"准入申请失败",
            "09":"开发申请失败",
            "10":"主数据申请失败",
            "11":"BPM申请成功",
            "12":"主数据申请"
        };
        let resultHtml = '';
        if(resp.data==''||resp.data==null){
            self.total = 0;
            self.isFirstPage = self.pageNo === 1;
            self.maxPage = 1;
            self.isLastPage = true;
        }else{
            self.total = resp.data.count;
            self.isFirstPage = self.pageNo === 1;
            self.maxPage = Math.ceil(self.total / self.pageSize);
            var aplySts = {
                '01':'已申请',
                '02':'一次审批通过',
                '03':'申请失败',
                '04':'申请成功',
            };
            $.each(resp.data.list,function(index,item){
                item.wdotCtt = item.wdotCtt ? item.wdotCtt : '';
                item.applyAvailabel = (item.aplySts==null || item.aplySts=='03'); // 未申请过的或申请失败的可以申请
                item.applyReactive = (item.aplySts=='04');  // 申请通过的可以申请重启用
                item.applyStatusName = aplySts[item.aplySts] || '';
                item.splrStsName = splrStatus[item.slprSts];
                index==0 && console.log(item,item.slprSts,splrStatus[item.slprSts]);
            });
            console.log(resp.data.list);
            // 处理数据end
            if (self.pageNo * self.pageSize >= self.total) {
                self.isLastPage = true;
            } else {
                self.isLastPage = false;
            }
            resultHtml = bidListTpl({ applyList: resp.data.list });
        }
        $('.J_apply-list').html(resultHtml);
    },

    // 渲染分页
    renderPagination: function() {
        let self = ApplyList;
        let pageList = [];
        for (let i = 0; i < self.maxPage; i++) {
            pageList.push({ idx: i + 1 });
        }
        let paginationHtml = paginationTpl({
            begin: (self.pageNo - 1) * self.pageSize + 1,
            end: self.isLastPage ? self.total : self.pageNo * self.pageSize,
            total: self.total,
            isLastPage: self.isLastPage,
            isFirstPage: self.isFirstPage,
            pageList: pageList

        });
        $('.J_pagination').html(paginationHtml);
        $('.page-item').each((index, item) => {
            if ($(item).data('index') === self.pageNo) {
                $(item).addClass('active');
            }
            var basepage = self.pageNo;
            if(basepage<=5){
                basepage = 5;
            }
            if((-5 <= (parseInt($(item).data('index'))-basepage)) && ((parseInt($(item).data('index'))-basepage)<=5)){
                $(item).removeClass('hidden');
                $(item).find("span").removeClass("hidden");
            }else{
                $(item).addClass('hidden');
                $(item).find("span").addClass("hidden");
            }
        });
    },

    // 绑定事件
    bindEvent: function() {
        let self = ApplyList;
        $('.J_prev').unbind().click(function() {
            if (self.pageNo > 1) {
                self.pageNo = self.pageNo - 1;
                self.getData()
                    .then(self.renderList)
                    .then(self.renderPagination)
                    .then(self.bindEvent);
            }
        });
        $('.J_next').unbind().click(function() {
            console.log('J_next');
            if (self.pageNo < self.maxPage) {
                self.pageNo = self.pageNo + 1;
                self.getData()
                    .then(self.renderList)
                    .then(self.renderPagination)
                    .then(self.bindEvent);
            }

        });
        $('.page-item').off().on('click', function() {
            let $item = $(this);
            console.log('aaaa');
            if (!$item.hasClass('active')) {
                self.pageNo = $item.data('index');
                self.getData()
                    .then(self.renderList)
                    .then(self.renderPagination)
                    .then(self.bindEvent);
            }
        });

        // 点击淘汰按钮时传参数  或重启用
        $(".btnSub").unbind().click(function(){
            var splrId = $(this).parent().parent().attr("splrId");
            var splrName = $(this).parent().parent().attr("splrNam");
            var action = $(this).attr("action");
            var titleName = '请输入'+(action=='wdot' ? '淘汰':'启用')+'[['+splrName+']] 理由';
            $("#myModalLabel").html(titleName);
            $("#myModalLabel").attr("splrId",splrId);
            $("#myModalLabel").attr("action",action);
        });

        var flg = true;
        // 淘汰供应商   or   淘汰供应商重新启用
        $(".endReason").unbind().click(function(){
            if(!flg){
                setTimeout(function(){flg=true;},3000);
                return false;
            }else{
                flg = false;
            }
            var splrId = $("#myModalLabel").attr("splrId");
            var action = $("#myModalLabel").attr("action");
            var aplyCtt = $(".endInfo").val();
            var data={"splrId":splrId,"aplyCtt":aplyCtt};
            var url='';
            if(action=='wdot'){
                url = HOST_ADDR + `/cpmp/splrWdot/aply`;
            }else{
                url = HOST_ADDR + `/cpmp/splrWdot/aply`;
                data={"splrId":splrId,"reActiveCtt":aplyCtt};
            }
            $.ajax({
                url: url,
                type: 'post',
                dataType: 'json',
                headers: {
                    'access_token': token,
                    'login_type': 'ums'
                },
                data:JSON.stringify(data),
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        // alert('申请成功');
                        $("#myModal").modal('hide')
                        if(action=='wdot'){
                            $("tr.odd[splrId="+splrId+"]").find(".operation").html("申请中");
                        }else{
                            $("tr.odd[splrId="+splrId+"]").find(".operation").html("申请启用中");
                        }
                        console.log(resp);
                        flg = true;
                    }
                    alert(resp.msgInf);
                    $("#myModal").modal('hide');
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });

        //搜索
        $('.searchSplr').unbind().click(function(){
            var searNam = jQuery('.searNam').val();
            self.pageNo = 1;
            self.data = {};
            if (searNam != '' && searNam != null) {
                self.data.splrNam = searNam;
            }
            console.log(self.data);
            self.getData()
                .then(self.renderList)
                .then(self.renderPagination)
                .then(self.bindEvent);
        });
    },
};

App.init();
ApplyList.init();

